package cn.com.yiqi.wsc.service.point.impl;

import cn.com.yiqi.wsc.Ro.PortalPointVO;
import cn.com.yiqi.wsc.common.Result;
import cn.com.yiqi.wsc.common.ResultStatusEnum;
import cn.com.yiqi.wsc.common.ResultUtil;
import cn.com.yiqi.wsc.dao.appparam.AppParamDao;
import cn.com.yiqi.wsc.dao.appparam.entity.AppParamEntity;
import cn.com.yiqi.wsc.dao.balance.BalanceRecordDao;
import cn.com.yiqi.wsc.dao.balance.entity.BalanceRecordEntity;
import cn.com.yiqi.wsc.dao.customer.CustomerMapper;
import cn.com.yiqi.wsc.dao.point.PointFetchMapper;
import cn.com.yiqi.wsc.dao.point.PointRecordDao;
import cn.com.yiqi.wsc.dao.point.criteria.PointCriteria;
import cn.com.yiqi.wsc.dao.point.entity.PointFetch;
import cn.com.yiqi.wsc.dao.point.entity.PointRecordEntity;
import cn.com.yiqi.wsc.entity.check.Check;
import cn.com.yiqi.wsc.entity.customer.Customer;
import cn.com.yiqi.wsc.enumeration.*;
import cn.com.yiqi.wsc.service.balance.enumeration.OperateType;
import cn.com.yiqi.wsc.service.check.CheckService;
import cn.com.yiqi.wsc.service.point.PortalPointService;
import cn.com.yiqi.wsc.service.sysparams.AppParamService;
import cn.com.yiqi.wsc.service.sysparams.dataobject.AppParamDO;
import cn.com.yiqi.wsc.service.user.UserService;
import cn.com.yiqi.wsc.util.AppParamUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

/**
 * @author 何刚
 * @version V1.0
 * @Title: PortalPointServiceImpl
 * @Package cn.com.yiqi.wsc.service.point.impl
 * @Description: TODO
 * Copyright: Copyright (c) 2016
 * Company: 成都壹柒互动科技有限公司
 * @date 2017/3/23
 */
@Service
public class PortalPointServiceImpl implements PortalPointService {


    @Autowired
    private PointRecordDao pointRecordDao;


    @Autowired
    private PointFetchMapper pointFetchMapper;

    @Autowired
    private CheckService checkService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private UserService userService;


    @Autowired
    private AppParamService appParamService;


    @Autowired
    private AppParamDao appParamDao;

    @Autowired
    private BalanceRecordDao balanceRecordDao;

    @Override
    public Result<PageInfo<PortalPointVO>> pageList(PointCriteria criteria) {

        Result<PageInfo<PortalPointVO>> infoResult = new Result<>();

        infoResult.setStatus(ResultStatusEnum.操作成功.getCode());

        PageHelper.startPage(criteria.getCurrentPage(), criteria.getPageSize());

        PageHelper.orderBy("mpf.d_apply_time DESC");

        PageInfo<PortalPointVO> pageInfo = new PageInfo<>(pointRecordDao.pageList(criteria));

        infoResult.setReturnValue(pageInfo);

        return infoResult;
    }


    @Transactional
    @Override
    public Result check(Check check) {

        Result result = new Result<>();
        result.setStatus(ResultStatusEnum.操作成功.getCode());

        check.setContentType(CheckTypeEnum.POINT_FETCH.getValue());

        PointFetch pointFetch = new PointFetch();
        pointFetch.setId(check.getContentId());

        pointFetch = pointFetchMapper.selectByPrimaryKey(pointFetch.getId());

        boolean access = CheckResultEnum.ACCESS.getValue() == check.getCheckResult();

        if (access) {
            pointFetch.setStatus(PointFetchType.pass.getValue().byteValue());
        } else {
            pointFetch.setStatus(PointFetchType.nopass.getValue().byteValue());
        }

        AppParamEntity entity = new AppParamEntity();
        entity.setCode(AppParamCode.POINT.getValue());
        AppParamDO paramDO = AppParamUtil.changeAPLToAPD(appParamDao.getMarryParamList(entity));

        String pointRate = paramDO.getPointRate();
        BigDecimal rate = new BigDecimal(pointRate);

        Integer point = pointFetch.getPoint();
        Integer customerId = pointFetch.getCustomerId();
        BigDecimal balance = rate.multiply(new BigDecimal(point));
        Integer userId = userService.getCurrentUserId();

        updatePointFetchStatus(pointFetch);

        //添加审核记录
        Result resultCheck = checkService.insertCheck(check);

        if (ResultUtil.isSuccess(resultCheck) && access) {
            //如果添加成功，并且是审核通过
            //添加余额
            updateCustomerBalance(customerId, balance);
        }

        if (!access) {
            //如果没有通过返还积分
            //加上积分，记录积分
            Customer customer = new Customer();
            customer.setId(customerId);
            customer.setPoint(point);
            customerMapper.updateCustomerPointByCustomerId(customer);
            savePointRecord(point, userId, customerId, PointRecordStatus.兑换余额, PointOperateTypeEnum.ADD, "兑换申请失败,积分返还");
        }
        return result;
    }

    private void updateCustomerBalance(Integer customerId, BigDecimal balance) {
        //修改用余额
        if (customerMapper.addBalance(balance, customerId) == 0) {
            //增加余额失败抛出异常
            throw new RuntimeException("增加余额失败");
        }

        //记录余额增加
        BalanceRecordEntity record = new BalanceRecordEntity();
        record.setDesc("积分提现");
        record.setCustomerId(customerId.longValue());
        record.setOperateTime(new Date());
        record.setOperateType(OperateType.ADD.getValue());
        record.setAmount(balance);
        record.setType(BalanceRecordType.积分兑换.getValue());
        balanceRecordDao.insert(record);
    }

    /**
     * 修改状态成功
     *
     * @param pointFetch
     * @return
     */
    private void updatePointFetchStatus(PointFetch pointFetch) {
        //修改申请记录状态
        if (pointFetchMapper.updateByPrimaryKeySelective(pointFetch) == 0) {
            //增加余额失败抛出异常
            throw new RuntimeException("增加余额失败");
        }
    }

    private void savePointRecord(Integer point, Integer userId, Integer customerId, PointRecordStatus pointRecordStatus, PointOperateTypeEnum pointOperateTypeEnum, String desc) {
        //添加积分记录
        PointRecordEntity pointRecordEntity = new PointRecordEntity();
        pointRecordEntity.setCustomerId(customerId.longValue());
        pointRecordEntity.setBizType(pointRecordStatus.getValue());
        pointRecordEntity.setOperateType(pointOperateTypeEnum.getValue());
        pointRecordEntity.setPoint(point);
        pointRecordEntity.setInsertTime(new Date());
        pointRecordEntity.setInsertUserId(userId);
        pointRecordEntity.setBizDesc(desc);

        if (pointRecordDao.insert(pointRecordEntity) == 0) {
            throw new RuntimeException("添加积分记录失败");
        }
    }


}
